<?php
/* Clase: Rewrite
 * Genera urls dinámicas al aire
--------------------------------------------- */
class rewrite {
	var $rules 	= array();
	var $index 	= 'index.php';
	var $str 	= array();

	var $rewritecode =
		array(
					'%year%',
					'%monthnum%',
					'%day%',
					'%hour%',
					'%minute%',
					'%second%',
					'%postname%',
					'%post_id%',
					'%author%',
					'%pagename%',
					'%search%'
					);

	var $rewritereplace =
		array(
					'([0-9]{4})',
					'([0-9]{1,2})',
					'([0-9]{1,2})',
					'([0-9]{1,2})',
					'([0-9]{1,2})',
					'([0-9]{1,2})',
					'([^/]+)',
					'([0-9]+)',
					'([^/]+)',
					'([^/]+?)',
					'(.+)'
					);

	var $queryreplace =
		array (
					'year=',
					'monthnum=',
					'day=',
					'hour=',
					'minute=',
					'second=',
					'name=',
					'p=',
					'author_name=',
					'pagename=',
					's='
					);
	
	// Constructor
	function __construct( $index = null ){
		if( !is_null($index) )
			$this->index = $index;

		$this->building_rules();
	}

	// Destructor
	function __destruct(){
		return true;
	}

	// Agrega nuevas reglas para las URLs dinamicas
	function add_rule( $permalink, $permalink_vars = null ){
		if( is_null($permalink_vars) ){
			preg_match_all('/%.+?%/', $permalink, $tokens);

			$permalink_in  = $permalink;
			$permalink_out = '';
			$index = 1;
			foreach( $tokens[0] as $token ){
				$key = array_search( $token, $this->rewritecode );
				$permalink_in   = str_replace( $token, $this->rewritereplace[$key], $permalink_in);
				$permalink_out .= ($index == 1 ? '' : '&') . $this->queryreplace[$key] . "\$" .'matches[' . $index . ']';
				++$index;
			}
			$this->rules["{$permalink_in}$"]=$permalink_out;
			return true;
		}
		$this->rules["{$permalink}$"]=$permalink_vars;
		return true;
	}

	// Agrega nuevas variables
	function add_variable( $rewrite_code, $rewrite_replace, $query_replace ){
		array_push( $this->rewritecode, $rewrite_code );
		array_push( $this->rewritereplace, $rewrite_replace );
		array_push( $this->queryreplace, $query_replace );
	}

	// Agrega reglas basicas del sistema
	function building_rules(){
		$this->rules = apply_filters( 'add_rules', $this->rules );
		
		$this->rules["sitemap.xml$"]    = "page=sitemap";
		$this->rules["feed.(xml|rss)$"] = "page=rss";
		$this->rules["(.+?)/?$"]        = "page=\$matches[1]";
	}
	
	// Realiza la verificacin
	function make(){
		$this->verify();
	}

	// Reconoce las urls
	function verify(){
		
		$site_url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
	
		$req_uri = $_SERVER['REQUEST_URI'];		
		$self = $_SERVER['PHP_SELF'];
		
		$home_path = parse_url($site_url);			
	
		
		if ( isset($home_path['path']) )
			$home_path = $home_path['path'];
		else
			$home_path = '';
		$home_path = trim($home_path, '/');			
		
		
		$req_uri = trim($req_uri, '/');
		$req_uri = preg_replace("|^$home_path|", '', $req_uri);
	
	
		$req_uri = trim($req_uri, '/');
	
		$self = trim($self, '/');
		$self = preg_replace("|^$home_path|", '', $self);
		$self = trim($self, '/');
		
		$this->msg($req_uri,"Extraemos el valor de la url");
	
		
			if ( $req_uri == $this->index )
				$req_uri = '';
			$request = $req_uri;

			
		$request2 = $request;
		

		$request_match = $request;
		foreach ($this->rules as $match => $query) {
	

			if ((! empty($req_uri)) && (strpos($match, $req_uri) === 0) && ($req_uri != $request)) {
				$request_match = $req_uri . '/' . $request;
			}
	
			if (preg_match("!^$match!", $request_match, $matches) ||
				preg_match("!^$match!", urldecode($request_match), $matches)) {
				
				$matched_rule = $match;
				
				$this->msg($matched_rule,"Obtenemos la regla a usar");
				
				$query = preg_replace("!^.+\?!", '', $query);
				
				
				$this->msg($query,"Obtenemos la marca a usar");

				eval("\$query = \"$query\";");
				$matched_query = $query;
				
				$this->msg($query,"Reemplazamos la marca con los valores extraidos");
	
				
				parse_str($query, $perma_query_vars);

				
				
				$this->msg($perma_query_vars,"Conversión de datos en Array para usarlos");
	
				
				break;
			}
		}		
				
	}
	
	function msg($code,$msgs=''){
		
		if (!empty($code)) {
			# code...
			$this->msgs[] = array( $code,$msgs);
		}
		
		
	}
	
	function print_msg(){
		$show="";
		
		if ($this->msgs) {
			# code...
		
			foreach($this->msgs as $msgcode):
				
				$show.= "<strong>".$msgcode[1]." </strong>:";
				$show.= "<pre>";
				$show.= print_r($msgcode[0], true);
				$show.= "</pre>";
				$show.= "<hr>";
					
			endforeach;
			
			return $show;
			
		}else {
			return false;
		}
		
		
	}

				# code...				
				
			
	
}
?>